<template>
  <div class="image-upload flex-col-center-start">
    <div class="header width-100-percent">
      <strong>
        图像上传
        <slot name="title"></slot>
      </strong>
<!--      <div style="float: right;right: 20px" class="clickable" @click="handleClose">-->
<!--        <el-icon><Close /></el-icon>-->
<!--      </div>-->
    </div>
    <div class="body flex-row-center  flex-wrap" >
      <!--    裁剪区-->
      <div class="flex-col-center-start">
        <!--      裁剪-->
        <Cropper :src="imageSrc" width="200px" height="200px" :scale="[1,1]" :resize="false" @crop="handleCropImage"></Cropper>
        <!--      预览-->
        <strong style="text-align: left;" class="width-100-percent">预览:</strong>
        <div class="preview-image margin-col-5">
          <img :src="cropImageSrc" class="preview-image" v-show="cropImageSrc !== ''"  alt="图片"/>
        </div>

      </div>
      <!--    上传区-->
      <div class="margin-row-40">
        <div class="flex-col-center">
          <el-upload
              ref="uploadRef"
              drag
              :headers="{
                token:sysConfig.TOKEN_PREFIX+getToken()
              }"
              :on-change="handleFileChange"
              :action="url"
              :on-success="handleSuccess"
              :on-error="handleError"
              :limit="1"
              :auto-upload="false"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽图片 或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                [ jpg 或 png ] (小于 2MB)
              </div>
            </template>
          </el-upload>
          <el-button @click="submit" style="width: 200px" :size="'large'" color="#222A42" :icon="UploadFilled">上传</el-button>
        </div>
      </div>
    </div>
    <div class="bottom"></div>
  </div>
</template>

<script setup lang="ts">
import Cropper, {CropBlob} from "@/components/image-cropper/Cropper.vue";
import { ref,defineProps,defineEmits,withDefaults} from "vue"
import { UploadFilled} from "@element-plus/icons";
import {ElMessage, UploadFile } from "element-plus";
import {base64ToFile, fileToBase64Async} from "@/utils/FileUtil";
import sysConfig from "@/config/index"
import {getToken} from "@/utils/TokenUtil";
// 后端上传地址

let uploadRef=ref()
// 原图片base64Url
let imageSrc=ref("")
// 裁剪后图片的base64Url
let cropImageSrc=ref("")

let props=withDefaults(defineProps<{
  url:string
  // 是否自动上传，是:点击上传返回图片URL; 否:点击上传返回图片base64Url
  autoUpload:boolean
}>(),{
  url:"",
  autoUpload:true
})
let emit=defineEmits<{
  (e:"upload",val:string):void
}>()
function handleCropImage(val:CropBlob){

  cropImageSrc.value=val.url
}
function handleFileChange(file:UploadFile){

  fileToBase64Async(file.raw,(url)=>{
    imageSrc.value=url
  })
}



function submit(){
  // clearFileList()
  // 非自动上传，返回图片base64Url
  if(!props.autoUpload){
    emit("upload",cropImageSrc.value)
    return
  }
  // 加入裁剪后的图片
  if(cropImageSrc.value !== ''){
    clearFileList()

    let toFile = base64ToFile(cropImageSrc.value);
    toFile.uid = new Date().getTime()
    uploadRef.value!.handleStart(toFile)
  }
  uploadRef.value.submit()
}
function clearFileList(){
  uploadRef.value!.clearFiles()
}

function handleSuccess(response: any, uploadFile: UploadFile){
  emit("upload",response.data)
  ElMessage({
    message:"上传成功",
    type:"success"
  })
}
function handleError(error:Error){
  ElMessage({
    message:"上传失败",
    type:"error"
  })
}


</script>

<style scoped lang="less">
  .image-upload{
    padding: 10px 30px 20px 30px;
    .body{
      .preview-image{
        width: 100px;
        height: 100px;
      }
    }
    .header{
      margin-bottom: 10px;
    }
  }
</style>